#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/4/4 16:37
# @Author  : JayWang
# @File    : dLoadSentinelOrbit.py
# @E_mail: 2394834585@qq.com
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By


def read(filePath):
    """
    获取需要下载的哨兵轨道数据名称
    :param filePath:需要的轨道数据文件信息，记事本文件
    :return:
    """
    s = []
    with open(filePath, 'r') as f:
        for line in f.readlines():
            line = line.strip('\n')
            s.append(line)
    # print(s)
    return s


def main(filePath):
    print("开始请求服务器，请稍等！")
    print("如果10分钟后仍未响应，请检查电脑是否可以打开以下网站：https://s1qc.asf.alaska.edu/aux_poeorb/")
    r = requests.get(url=r"https://s1qc.asf.alaska.edu/aux_poeorb/")

    # 请求成功
    if r.status_code == 200:
        # 解析网页
        soup = BeautifulSoup(r.text, 'html.parser')
        time.sleep(1)
        # print(soup)
        print("*" * 15 + "请求成功！尝试开始下载数据" + "*" * 15)

    # 请求失败
    else:
        print("*" * 15 + "请求失败，请尝试更换网络！" + "*" * 15)
        return 0

    # 开始下载
    print("开始解析文件日期")
    s = read(filePath)

    # 使用驱动来打开earthdata官网,并登录
    information = read(r'./Account.txt')
    # driver = webdriver.Chrome()
    driver = webdriver.Edge()
    driver.get("https://urs.earthdata.nasa.gov/")
    account = driver.find_element(by=By.NAME, value='username')
    account.send_keys("{}".format(information[0]))
    password = driver.find_element(by=By.NAME, value='password')
    password.send_keys("{}".format(information[1]))
    time.sleep(5)
    driver.find_element(by=By.NAME, value="commit").click()

    # 获取所以a标签
    a_s = soup.find_all('a')
    Xs = []
    for a in a_s:
        # print(a['href'])
        Xs.append(a['href'])
    # print(s, len(Xs), Xs[10])
    for line in s:
        # print(line)
        # 遍历找寻看是否有对应日期的精密轨道
        for i in range(0, len(Xs)):
            # 如果找到，则下载保存
            if (line[0: 3] in Xs[i]) and (line[4: 13] in Xs[i]):
                print("OK！已找到日期：" + line[5: 13] + "对应的精密轨道，正在下载……")
                # 构造精密轨道文件的网址
                url = "https://s1qc.asf.alaska.edu/aux_poeorb/" + Xs[i]
                print(url)
                # 请求网址
                driver.get(url)
                # 获取精密轨道数据
                time.sleep(5)
                data = driver.find_element(by=By.XPATH, value="/html/body")
                # 保存到本地
                with open(r"./orbit/{}".format(Xs[i]), 'w', encoding='utf-8') as f:
                    f.write(data.text)
                    f.close()
                # print(data.text)
                print("日期：" + line[5: 13] + "对应的精密轨道，成功下载！")
                print()
                break
            else:
                i += 1
            # 如果没找到，就提示报错
            if i == len(Xs):
                print("Error！未找到日期：" + line[5: 13] + "对应的精密轨道，")
                print("日期：" + line[5: 13] + "对应的精密轨道，未能下载！")
                print("!" * 15 + "精密轨道需要在20天左右以后才可下载，请检查数据日期、卫星名称等是否正确或电脑是否联网" + "!" * 15)
                print()
    # 关闭浏览器驱动
    driver.close()
    # 退出控制台
    exit(0)


if __name__ == "__main__":
    main(r"./date.txt")
